package com.nervenets.web;

import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.entity.Result;
import com.nervenets.web.i18n.Translator;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@ControllerAdvice
public class ApplicationExceptionHandler {
    /**
     * 所有异常报错
     *
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String allExceptionHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ex.printStackTrace();
        StringBuilder params = new StringBuilder();
        params.append(JodaUtils.timeLongToString(JodaUtils.getTimestamp() * 1000L, "MM-dd HH:mm:ss")).append("\n");
        StackTraceElement[] stackTrace = ex.getStackTrace();
        for (StackTraceElement element : stackTrace) {
            if (element.toString().contains("com.nervenets")) {
                params.append(element.getFileName()).append(":").append(element.getLineNumber()).append("\n");
            }
        }
        Map map = request.getParameterMap();
        for (Object key : map.keySet()) {
            params.append(key).append(":").append(request.getParameter(String.valueOf(key))).append("\n");
        }
        StringBuffer requestURL = request.getRequestURL();
        String errorMessage = params.toString() + requestURL + "\nerror:" + ex.getMessage();

        Result result = Result.failed();
        result.setCode(MessageCode.code_500);
        result.setData(errorMessage);
        result.setVersion("1.0");
        result.setMessage(Translator.translate("code_500"));
        return StringUtils.toJson(result);
    }
}
